package com.xcc.util;

import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;

/**
 * @outhor Ren
 * @create 2019-03-21 22:25
 * 描述:
 */
@Slf4j
public class JsonMapper {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
    }


    /**
     * 将对象转换为字符串
     *
     * @param src
     * @param <T>
     * @return
     */
    public static <T> String obj2String(T src) {
        if (src == null) return null;
        try {
            // 如果是字符串，强制转换后返回字符串。 如果不是字符串，使用 objectMapper 将对象转转换为字符串
            return src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("parse object to String exception， error:{}", e);
            return null;
        }
    }

    /**
     * 将字符串转换为对象
     *
     * @param src
     * @param tTypeReference
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String src, TypeReference<T> tTypeReference) {
        if (src == null || tTypeReference == null) return null;
        try {
            return (T) (tTypeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, tTypeReference));
        } catch (Exception e) {
            log.warn("parse String to object exception, String: {}, TypeReference<T>:{}, error:{}", src, tTypeReference, e);
            return null;
        }

    }
}
